package com.stations.task;

import com.stations.domain.TTransmitter;
import com.stations.domain.TTransmitterProgram;
import com.stations.mapper.TTransmitterMapper;
import com.stations.mapper.TTransmitterProgramMapper;
import com.stations.service.TrasmiterService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


/**
 * TimeTask
 *
 * @author jintao
 * @version 2023/07/12 14:56
 **/
@Component
@EnableScheduling
@Slf4j
public class TimeTask {

    @Resource
    private TrasmiterService sysTrasmiterService;
    @Resource
    TTransmitterMapper transmitterMapper;
    @Resource
    private TTransmitterProgramMapper tTransmitterProgramMapper;

    @SneakyThrows
    @Scheduled(cron = "0/1 * * * * ? ")
    public void task() {
        List<TTransmitter> lisTTransmitter = sysTrasmiterService.getAllTransmitter();
        for (TTransmitter tTransmitter : lisTTransmitter) {
            long beginTimestamp = tTransmitter.getSendTime().getTime(); // 开始时间戳
            long endTimestamp = new Date().getTime();     // 结束时间戳
            long difference = endTimestamp - beginTimestamp; // 时间差，单位为毫秒
            long seconds  = difference / 1000; // 时间差，单位为小时
            if(seconds>10){
                tTransmitter.setStatus(1);
                if("0".equals(tTransmitter.getStatus())){
                    TTransmitterProgram tTransmitterProgram = new TTransmitterProgram();
                    tTransmitterProgram.setStationCode(tTransmitter.getStationCode());
                    tTransmitterProgram.setTransCode(tTransmitter.getTransCode());
                    List<TTransmitterProgram> list = tTransmitterProgramMapper.selectTTransmitterProgramList(tTransmitterProgram);
                    for (int i = 0; i < list.size(); i++) {
                        tTransmitterProgram.setFlag("0");
                        tTransmitterProgramMapper.updateById(tTransmitterProgram);
                    }
                }
            }else{
                tTransmitter.setStatus(0);
            }
            transmitterMapper.updateByMultiId(tTransmitter);
        }
    }

    /**
     * 获取当前日期是星期几<br>
     *
     * @param date
     * @return 当前日期是星期几
     */
    public String getWeekOfDate(Date date) {
        String[] weekDays = {"7", "1", "2", "3", "4", "5", "6"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

}
